﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace GoodStuff.Web.Controls
{
    public class CheckBoxRequiredFieldValidator : System.Web.UI.WebControls.BaseValidator
    {
        private CheckBox _checkbox;

        public CheckBoxRequiredFieldValidator()
        {
        }

        protected override bool ControlPropertiesValid()
        {
            Control ctrl = FindControl(ControlToValidate);

            if (ctrl != null)
            {
                _checkbox = ctrl as CheckBox;
                return (_checkbox != null);
            }
            else
                return false;  // raise exception
        }

        protected override bool EvaluateIsValid()
        {
            return _checkbox.Checked;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (this.EnableClientScript)
            {
                // Register the client-side function using WebResource.axd (if needed)
                // see: http://aspnet.4guysfromrolla.com/articles/080906-1.aspx
                if (this.RenderUplevel && this.Page != null && !this.Page.ClientScript.IsClientScriptIncludeRegistered(this.GetType(), "goodStuffValidators"))
                {
                    string url = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "GoodStuff.Web.Controls.GoodStuffValidators.js");
                    ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "goodStuffValidators", url);
                }
            }
        }


        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);

            if (this.EnableClientScript)
            {
                // Add the client-side code (if needed)
                if (this.RenderUplevel)
                {
                    writer.AddAttribute("evaluationfunction", "CheckBoxValidatorEvaluateIsValid", false);
                }
            }
        }
    }
}
